package map.tile.server.service.impl;

import map.tile.server.bo.MongodbTile;
import map.tile.server.dto.TileIndex;
import map.tile.server.service.MongodbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
public class MongodbServiceImpl implements MongodbService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void createCollection(String name) {
        if (!isCollectionExist(name)) {
            mongoTemplate.createCollection(name);
            //创建mongodb数据库中的索引
            Index index = new Index();
            index.on("x", Sort.Direction.ASC);
            index.on("y", Sort.Direction.ASC);
            index.on("z", Sort.Direction.ASC);
            index.unique();
            mongoTemplate.indexOps(name).ensureIndex(index);
        }
    }

    @Override
    public void saveTile(MongodbTile mongodbTile, String collectionName) {
//        mongoTemplate.save(mongodbTile,collectionName);
        mongoTemplate.upsert(new Query(Criteria.where("x").is(mongodbTile.getX())
                        .and("y").is(mongodbTile.getY())
                        .and("z").is(mongodbTile.getZ())
                ),
                new Update().set("tile", mongodbTile.getTile()).set("x", mongodbTile.getX()).set("y", mongodbTile.getY()).set("z", mongodbTile.getZ()), collectionName);

    }

    @Override
    public MongodbTile getTile(TileIndex tileIndex) {
        Query query = new Query();
        Criteria criteria = Criteria.where("x").is(tileIndex.getX());  //查询条件"id"指MongoDB里面的key
        criteria.and("y").is(tileIndex.getY());  //and条件
        criteria.and("z").is(tileIndex.getZ());  //and条件
        query.addCriteria(criteria);
        return mongoTemplate.findOne(query, MongodbTile.class, tileIndex.getCollectionName());
    }


    @Override
    public boolean isCollectionExist(String name) {
        return mongoTemplate.collectionExists(name);
    }


//    //一般查询
//    Query query = new Query();
//    Criteria criteria = Criteria.where("id").is(id);  //查询条件"id"指MongoDB里面的key
//            criteria.and("name").is(name);  //and条件
//            query.addCriteria(criteria);
//    MyTest myTest = mongoTemplate.findOne(query,MyTest.class,"myTest");
}
